package com.zy.stock.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.zy.stock.domain.Pager;
import com.zy.stock.domain.Stock;
import com.zy.stock.domain.StockTranscation;
import com.zy.stock.domain.UserStockRl;
import com.zy.stock.dto.StockDto;
import com.zy.stock.dto.StockTranscationDto;
import com.zy.stock.dto.UserStockRlDto;
import com.zy.stock.dto.UserStockRlProfitDto;
import com.zy.stock.mapper.StockMapper;
import com.zy.stock.mapper.StockTranscationMapper;
import com.zy.stock.mapper.UserStockRlMapper;
import com.zy.stock.service.UserStockRlService;
import com.zy.stock.util.CommonUtils;

@Transactional
@Component
public class UserStockRlServiceImpl implements UserStockRlService{
	
	private Logger logger = LoggerFactory.getLogger(UserStockRlServiceImpl.class);
	
	@Autowired
	private UserStockRlMapper userStockRlMapper;
	
	@Autowired
	private StockMapper stockMapper;
	
	@Autowired
	private StockTranscationMapper stockTranscationMapper;
	
	@Override
	public Pager<List<UserStockRl>> findByCase(Pager<UserStockRlDto> pager)
			throws Exception {
		// TODO Auto-generated method stub
		Pager<List<UserStockRl>> result = new Pager<List<UserStockRl>>();
		try{
			UserStockRlDto obj = pager.getT();
			Integer total = userStockRlMapper.getCount(obj);
			Integer totalpage = CommonUtils.getTotalPage(pager, total);
			Integer begin = (pager.getPagenow() - 1) * pager.getSize();
			obj.setStart(begin);
			obj.setSize(pager.getSize());
			obj.setOrder(pager.getOrder());
			obj.setOrderCol(pager.getOrderCol());
			List<UserStockRl> list = userStockRlMapper.findByCase(obj);
			//处理显示浮动盈亏
			for(UserStockRl rl:list){
				//计算累计盈亏收益率
				StockTranscationDto dto = new StockTranscationDto();
				dto.setUserStockRlId(rl.getId());
				dto.setStatus("已完成");
				List<StockTranscation> transcations = stockTranscationMapper.findByCase(dto);
				rl.setEarningsRate(calculateEarningRate(transcations, rl));
				//计算浮动盈亏
				Double earnings = calculateEarnings(rl);
				rl.setEarnings(earnings);
			}
			result.setTotal(total);
			result.setT(list);
			result.setTotalpage(totalpage);
		}catch(Exception e){
			e.printStackTrace();
			throw new Exception("UserStockRlServiceImpl.class findByCase function error : " + e.toString());
		}
		return result;
	}
	
	/** 计算累计盈亏收益率
	 * 
	 * @param transcations
	 * @return
	 */
	private String calculateEarningRate(List<StockTranscation> transcations,UserStockRl rl){
	  //市值
	  Stock stock = stockMapper.findById(rl.getStockId());
	  double values = rl.getNum()*stock.getValue();
	  //收入
	  double incomeCash = 0;
	  //支出
	  double payCash = 0;
	  for(StockTranscation st:transcations){
	    if(st.getIncomeCash()!=null){
	        incomeCash+=st.getIncomeCash().doubleValue();
	    }
	    if(st.getPayCash()!=null){
	        payCash+=st.getPayCash().doubleValue();
	    }
	  }   
	  //收益率为 (总收入－总支出+市值)/总支出＊100%
	  double rate = (values+incomeCash-payCash)*100/payCash;
	  int staticEarnings = (int)(values+incomeCash-payCash);
	  rl.setStaticEarnings(Double.valueOf(staticEarnings));
	  BigDecimal rateBig = new BigDecimal(rate);
	  rateBig = rateBig.setScale(2, BigDecimal.ROUND_HALF_UP);
	  return rateBig.toString()+"%";
	}
	
	@Override
	public Integer save(UserStockRl obj) throws Exception {
		// TODO Auto-generated method stub
		obj.setCreateTime(new Date());
		return userStockRlMapper.save(obj);
	}

	@Override
	public void deleteById(Integer id) throws Exception {
		// TODO Auto-generated method stub
	  StockTranscationDto dto = new StockTranscationDto();
	  UserStockRl rl = userStockRlMapper.findById(id);
	  dto.setUserStockRlId(id);
	  List<StockTranscation> sts = stockTranscationMapper.findByCase(dto);
	  for(StockTranscation st:sts){
	    stockTranscationMapper.deleteById(st.getId());
	  }
	  userStockRlMapper.deleteById(id);
	}

	@Override
	public void update(UserStockRl userStockRl) throws Exception {
		// TODO Auto-generated method stub
		userStockRl.setUpdateTime(new Date());
		userStockRlMapper.update(userStockRl);
	}

	@Override
	public UserStockRl findById(Integer id) throws Exception {
		// TODO Auto-generated method stub
		return userStockRlMapper.findById(id);
	}

	@Override
	public Double getCost(Integer operateNum, Double suggestValue,String stockCode) {
		// TODO Auto-generated method stub
		Double buyCost = suggestValue * operateNum;//股票买入总金额
		Double yongJin = new Double(0);//券商佣金 按每次下单股票买入总金额的0.025%收取，但最低为5元；
		if(buyCost*0.00025>=5){
			yongJin = buyCost*0.00025;
		}else{
			yongJin = 5d;
		}
		Integer guohuFei = 0;
		if(stockCode.startsWith("6")){
			BigDecimal cost = new BigDecimal(operateNum/1000);
			guohuFei = cost.intValue();
		}
		return (buyCost+yongJin+guohuFei)/operateNum;
	}

	@Override
	public List<UserStockRl> findLastUserStockRl(Integer userId,Integer stockId, String years) {
		// TODO Auto-generated method stub
		return userStockRlMapper.findLastUserStockRl(userId, stockId, years);
	}

	@Override
	public List<UserStockRl> findByCode(String code) {
		// TODO Auto-generated method stub
		return userStockRlMapper.findByCode(code);
	}
	
	/**
	 * 计算浮动盈亏
	 */
	public double calculateEarnings(UserStockRl rl){
		BigDecimal earnings = new BigDecimal(0);
		Integer companyCost = 0;//券商佣金
		Integer guoHuCost = 0;//过户费
		Integer yinHuaCost = 0;//印花税
		
		Integer sellNum = rl.getNum();//卖出数
		
		if(sellNum>0){
			Stock stock = stockMapper.findById(rl.getStockId());
			Double stockCost = sellNum*stock.getValue();//成交金额
			Double totalCost = rl.getCost()*rl.getNum();//持有量*成本 为当前成本
			companyCost = (int) (stockCost*0.00025);
			
			if(companyCost<=5){
				companyCost = 5;
			}
			logger.info("得到券商佣金 is..."+companyCost);//得到券商佣金
			
			if(stock.getCode().indexOf("6")==0){
				guoHuCost = sellNum/1000;
				if(guoHuCost<=1){
					guoHuCost = 1;
				}
			}
			
			logger.info("得到过户费 is..."+guoHuCost);//得到过户费
			
			yinHuaCost = (int) (stockCost*0.001);//得到印花税
			logger.info("得到印花税 is..."+yinHuaCost);
			
			//根据成本、成交金额得到最后的浮动盈亏值
			earnings = new BigDecimal(stockCost-companyCost-guoHuCost-yinHuaCost-totalCost);
			
		    double rate = earnings.doubleValue()*100/totalCost;
		    BigDecimal rateBig = new BigDecimal(rate);
		    rateBig = rateBig.setScale(2, BigDecimal.ROUND_HALF_UP);
		    rl.setFloatEarningsRate(rateBig.toString()+"%");
			earnings = earnings.setScale(2, BigDecimal.ROUND_HALF_UP);
		}else{
		    rl.setFloatEarningsRate("无");
			return 0d;
		}
		return earnings.doubleValue();
	}

	@Override
	public double calculateStaticEarnings(UserStockRl rl) {
		// TODO Auto-generated method stub
		return 0;
	}

  @Override
  public UserStockRl findByStoreNum(String storeNum) {
    return userStockRlMapper.findByStoreNum(storeNum);
  }

  @Override
  public List<UserStockRlProfitDto> findRlProfit(UserStockRlDto dto) {
    // TODO Auto-generated method stub
    return userStockRlMapper.findRlProfit(dto);
  }
	
}
